import { http } from "@/utils/http";
import type { ApiResponse } from "../../user";
import { ensureArray, normalisePagination, toNumber } from "@/api/_helpers";
import {
  cleanupQuery,
  mapMedia,
  mapParticipant,
  toOptionalNumber,
  type AssistUserRef,
  type MediaAttachment,
  type ParticipantRef,
  type ProductPreview,
  type RegionRef
} from "./_shared";

const INQUIRY_BASE = "/system/verify/inquiry";

export type {
  MediaAttachment,
  ParticipantRef,
  AssistUserRef,
  RegionRef,
  ProductPreview
} from "./_shared";

export interface InquiryListItem {
  id: number;
  inquiry_no: string;
  status: number;
  status_label: string;
  buyer_qty: number;
  buyer_expected_price: number | null;
  buyer_expected_date: string | null;
  buyer_remark: string;
  buyer_media: MediaAttachment;
  buyer_time: string;
  buyer: ParticipantRef;
  seller_price: number | null;
  seller_delivery_date: string | null;
  seller_remark: string;
  seller_media: MediaAttachment;
  seller_time: string;
  seller: ParticipantRef;
  assist_user_id: number | null;
  assist_user?: AssistUserRef;
  region_id: number | null;
  region?: RegionRef;
  quote_count: number;
  last_quote_time: string;
  snapshot_product: Record<string, any>;
  product_id: number;
  product?: ProductPreview;
  sku_id: number | null;
  order_id: number | null;
  order_no: string;
  create_time: string;
  update_time: string;
}

export interface InquiryListParams {
  page?: number;
  page_size?: number;
  keyword?: string;
  status?: number | string;
  buyer_id?: number | string;
  buyer_org_id?: number | string;
  seller_id?: number | string;
  seller_org_id?: number | string;
  region_id?: number | string;
  assist_user_id?: number | string;
}

export interface InquiryListResult {
  list: InquiryListItem[];
  pagination: {
    total: number;
    pageSize: number;
    currentPage: number;
  };
  raw: Record<string, any>;
}

export type InquiryDetail = InquiryListItem;

const mapInquiryItem = (item: Record<string, any>): InquiryListItem => {
  const buyer = mapParticipant(
    item.buyer as Record<string, any> | undefined,
    item.buyer_id,
    item.buyer_org_id
  );

  const seller = mapParticipant(
    item.seller as Record<string, any> | undefined,
    item.seller_id,
    item.seller_org_id
  );

  return {
    id: toNumber(item.id, 0),
    inquiry_no: item.inquiry_no ?? "",
    status: toNumber(item.status, 0),
    status_label: item.status_label ?? "",
    buyer_qty: toNumber(item.buyer_qty, 0),
    buyer_expected_price:
      item.buyer_expected_price !== undefined &&
      item.buyer_expected_price !== null
        ? Number(item.buyer_expected_price)
        : null,
    buyer_expected_date: item.buyer_expected_date ?? null,
    buyer_remark: item.buyer_remark ?? "",
    buyer_media: mapMedia(item.buyer_media),
    buyer_time: item.buyer_time ?? "",
    buyer,
    seller_price:
      item.seller_price !== undefined && item.seller_price !== null
        ? Number(item.seller_price)
        : null,
    seller_delivery_date: item.seller_delivery_date ?? null,
    seller_remark: item.seller_remark ?? "",
    seller_media: mapMedia(item.seller_media),
    seller_time: item.seller_time ?? "",
    seller,
    assist_user_id: toOptionalNumber(item.assist_user_id),
    assist_user: item.assist_user
      ? {
          id: toNumber(item.assist_user.id ?? item.assist_user_id, 0),
          name: item.assist_user.name ?? ""
        }
      : undefined,
    region_id: toOptionalNumber(item.region_id),
    region: item.region
      ? {
          id: toNumber(item.region.id ?? item.region_id, 0),
          name: item.region.name ?? ""
        }
      : undefined,
    quote_count: toNumber(item.quote_count, 0),
    last_quote_time: item.last_quote_time ?? "",
    snapshot_product: (item.snapshot_product as Record<string, any>) ?? {},
    product_id: toNumber(item.product_id, 0),
    product: item.product
      ? {
          id: toNumber(item.product.id ?? item.product_id, 0),
          title: item.product.title ?? "",
          model: item.product.model ?? ""
        }
      : undefined,
    sku_id: toOptionalNumber(item.sku_id),
    order_id: toOptionalNumber(item.order_id),
    order_no: item.order_no ?? "",
    create_time: item.create_time ?? "",
    update_time: item.update_time ?? ""
  };
};

const fetchList = async (
  params: InquiryListParams = {}
): Promise<InquiryListResult> => {
  const page = toNumber(params.page, 1);
  const pageSize = toNumber(params.page_size, 10);

  const query = cleanupQuery({
    ...params,
    page,
    page_size: pageSize
  });

  const res = await http.request<ApiResponse<any>>("get", INQUIRY_BASE, {
    params: query
  });

  const payload = (res?.data as Record<string, any>) ?? {};
  const list = ensureArray<Record<string, any>>(payload.list ?? payload.data)
    .filter(Boolean)
    .map(mapInquiryItem);

  const pagination = normalisePagination(
    payload.pagination ?? payload,
    page,
    pageSize,
    list.length
  );

  return {
    list,
    pagination,
    raw: payload
  };
};

const fetchDetail = async (id: number | string): Promise<InquiryDetail> => {
  const res = await http.request<ApiResponse<any>>(
    "get",
    `${INQUIRY_BASE}/${id}`
  );
  const payload = (res?.data as Record<string, any>) ?? {};
  return mapInquiryItem(payload);
};

export default {
  fetchList,
  fetchDetail
};
